"""
Author : ZhengShiQi
DateTime: 2025/9/12 11:35
FileName: wiremock_manager.py
description: 控制WireMock服务的工具类
"""
import logging

import requests
from app.config import settings
from app.models.schemas import MockApiCreate
# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class WireMockManager:
    def __init__(self):
        self.base_url = settings.WIREMOCK_URL
        self.bind_address = settings.WIREMOCK_BIND_ADDRESS
    
    def create_mock_mapping(self, mock_config: MockApiCreate):
        """创建WireMock映射"""
        mapping = {
            "request": {
                "method": mock_config.method,
                "url": mock_config.url
            },
            "response": {
                "status": mock_config.response_status,
                "jsonBody": mock_config.response_body
            }
        }
        
        response = requests.post(f"{self.base_url}/__admin/mappings", json=mapping)
        response.raise_for_status()
        return response.json()
    
    def delete_mock_mapping(self, mapping_id: str):
        """删除WireMock映射"""
        response = requests.delete(f"{self.base_url}/__admin/mappings/{mapping_id}")
        response.raise_for_status()
        return response.status_code == 200
    
    def update_mock_mapping(self, mapping_id: str, mock_config: MockApiCreate):
        """更新WireMock映射"""
        mapping = {
            "request": {
                "method": mock_config.method,
                "url": mock_config.url
            },
            "response": {
                "status": mock_config.response_status,
                "jsonBody": mock_config.response_body
            }
        }
        logger.info(f"这是wiremock映射的body对象{type(mock_config.response_body)}")
        response = requests.put(f"{self.base_url}/__admin/mappings/{mapping_id}", json=mapping)
        response.raise_for_status()
        return response.json()
